package org.djw.basic.interceprot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceprot implements HandlerInterceptor{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //获取请求头中由axios前置拦截器携带的token
        String token = request.getHeader("token");
        //判断redis中是否有对应的token
        if (!StringUtils.isEmpty(token)){
            //如果有,判断redis中存储的值是否过期
            Object loginTmp = redisTemplate.opsForValue().get(token);
            if (loginTmp != null){
                //没过期,刷新过期时间
                redisTemplate.opsForValue().set(
                        token,
                        loginTmp,
                        30,
                        TimeUnit.MINUTES);
                //放行
                return true;
            }
        }
        //否则报错,不放行
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }
}
